package service;

import java.util.ArrayList;
import java.util.List;

import javax.swing.table.DefaultTableModel;

import dao.CourDao;
import dao.StuDao;
import model.*;
public class CourseService {
	CourDao courDao = new CourDao();
	//查询全部课程
	public List <Course> findAllCourse(){
		List <Course> cours = courDao.findAll();
		return cours;
	}
	
	//根据id查询课程
	public List <Course> findCourseById(int id){
		List <Course> cours = courDao.findCourseById(id);
		return cours;
	}
	
	//根据name查询课程
	public List <Course> findCourseByName(String name){
		List <Course> cours = courDao.findCourseByName(name);
		return cours;
	}

	//添加课程
	public boolean insertCourse (String id , String name , String period){
		try{
			Course cour = new Course(Integer.parseInt(id),name,Integer.parseInt(period));
			return courDao.insertCourse(cour);
		}
		catch(NumberFormatException e){
			return false;
		}
	}
	
	//根据id删除课程
	public boolean deleteCourseById(String id){
		try{
			int deleteId = Integer.parseInt(id);
			return courDao.deleteCourseById(deleteId);
		}catch(Exception e){
			return false;
		}
	}
	
	//根据文本框的内容进行查询，并显示到表格上
	public void searchAndShow(String input , DefaultTableModel tm){
		List <Course> cours = null;
		if(input.equals("")){
			cours = findAllCourse();
		}
		else{
			try{
				int id = Integer.parseInt(input);
				cours = findCourseById(id);
				if(cours.size() == 0){
					cours = findCourseByName(input);
				}
					
			}
			catch(NumberFormatException e1){
				cours = findCourseByName(input);
			}
		}
		tm.setRowCount(0);
		for(Course cour : cours){
			String [] row={cour.getId()+"",cour.getCname(),cour.getPeriod()+""};
			tm.addRow(row);
		}
	}
	
	//修改课程
	public boolean updateCourse (String id , String name , String period){
		try{
			Course cour = new Course(Integer.parseInt(id),name,Integer.parseInt(period));
			return courDao.updateCourse(cour);
		}
		catch(NumberFormatException e){
			return false;
		}
	}
	
}
